﻿using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Data;
using System.Deployment.Internal;
using DataAccessLayer;

namespace BusinessLayer
{

    /// <summary>
    /// The repository.
    /// </summary>
    public class Repository<T> where T : BusinessEntity, new()
    {
        private string GetType()
        {
            string[] str = typeof(T).ToString().Split('.');
            return str[str.Length-1];
            
        }

        /// <summary>
        /// Read all.
        /// </summary>
        public virtual Reader<T> ReadAll(int id = -1)
        {
            return new Reader<T>((DataAccessLayer.Reader)DAL.Operation("Read", GetType(), new Dictionary<string, object> {{"Id", id}}));
        }

        /// <summary>
        /// Read the entity by id.
        /// </summary>
        public virtual T ReadById(int id)
        {
            T entity = new T();
            entity.Initialize((Dictionary<string, object>)DAL.Operation("ReadById", GetType(), new Dictionary<string, object> { { "Id", id } }));
            return entity;
        }

        /// <summary>
        /// Create an entity.
        /// </summary>
        public virtual T Create()
        {
            T entity = new T();
            entity.Initialize((Dictionary<string, object>)DAL.Operation("Create", GetType(), null));
            return entity;
        }

        /// <summary>
        /// Write the entity in DB.
        /// </summary>
        /// <exception cref="DataException">
        /// </exception>
        public virtual void Write(BusinessEntity entity)
        {
            DAL.Operation("Write", GetType(), BusinessEntity.ToDalEntity(entity));
        }

        /// <summary>
        /// Remove the entity.
        /// </summary>
        /// <exception cref="DataException">
        /// </exception>
        public virtual void Remove(int id)
        {
            DAL.Operation("Remove", GetType(), new Dictionary<string, object> {{"Id", id}});
        }
    }
}
